import store from "@/Vuex/store.js"
import config from "./config"
let baseUrl = config.baseUrl
let reqCount = 0,
	resCount = 0; //记录请求次数和响应次数

const request = ({
	loading = false, //是否显示加载动画
	url, //接口地址后缀
	method = "GET", //请求方式
	data = {}, //请求参数
	header = {}, //请求头
	upload = false,
}) => {
	//reqCount++;
	if (loading) {
		//默认不显示loading，配置loading为true显示
		uni.showLoading({
			title: '加载中...',
			mask: true
		});
	}
	let token = uni.getStorageSync('token') || '';
	if (upload) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: baseUrl + url,
				filePath: data,
				name: 'file',
				header: {
					...header,
					Authorization: 'Bearer ' + token
				},
				formData: {},
				success: (uploadFileRes) => {
					//resCount++
					let data = JSON.parse(uploadFileRes.data);
					if (data.code == 200) {
						resolve(data.url);
					} else {
						if (data.code === 401) {
							store.commit('setUserInfo', null);
							uni.showToast({
								title: `登录过期，请重新登录`,
								icon: 'none',
								success: (t) => {
									uni.reLaunch({
										url: '/pages/login/index'
									})
								}
							})
						} else {
							uni.showToast({
								title: data.msg,
								icon: "none"
							});
						}
						reject(data);
					}
				},
				fail: (error) => {
					//resCount++
					uni.showToast({
						title: '上传失败',
						icon: "none"
					});
					reject('上传出错了');
				}
			});
		})
	} else {
		let copyData = JSON.parse(JSON.stringify(data))
		for (let key in copyData) {
			if (copyData[key] == null || copyData[key] == undefined) {
				delete copyData[key]
			}
		}
		return new Promise((resolve, reject) => {
			uni.request({
				sslVerify: false,
				method: method,
				url: baseUrl + url,
				data: copyData,
				header: {
					...header,
					Authorization: 'Bearer ' + token
				}
			}).then((response) => {
				// resCount++
				// if (reqCount === resCount) 
				if (loading) {
					uni.hideLoading(); //防止连续请求多个接口时loading闪现
				}
				let [error, res] = response;
				if (res.data.code === 200) {
					// 接口返回数据正常
					resolve(res.data);
				} else {
					if (res.data.code === 401) {
						store.commit('setUserInfo', null);
						uni.showToast({
							title: `登录过期，请重新登录`,
							icon: 'none',
							success: (t) => {
								uni.reLaunch({
									url: '/pages/login/index'
								})
							}
						})
					} else {
						uni.showToast({
							title: res.data.msg || "请求接口出错，请联系管理员",
							icon: "none"
						});
					}
					reject(res.data);
				}
			}).catch(error => {
				// 请求异常
				// resCount++
				// if (reqCount === resCount) 
				if (loading) {
					uni.hideLoading();
				}

				uni.showToast({
					title: "网络正在开小差，请重新连接网络",
					icon: "none"
				});
				let [err, res] = error;
				reject(err)
			})
		});
	}
}
export default request